package com.vf.admin.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.*;
import com.vf.admin.client.service.AppInvitationRecordService;
import com.vf.admin.client.service.AppPrivilegeService;
import com.vf.admin.client.service.AppSetupService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.client.tx.vo.UserShiZhi;
import com.vf.admin.client.tx.vo.userSignVo;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.vf.admin.utils.StringEx.isNull;
import static com.vf.admin.utils.UseDate.getDay;

@Service
public class AppPrivilegeServiceImpl extends BaseController implements AppPrivilegeService {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AppUserDao appUserDao;

    @Autowired
    AppPrivilegeDao appPrivilegeDao;

    @Autowired
    AppMountsDao appMountsDao;

    @Autowired
    AppHeadwearDao appHeadwearDao;

    @Autowired
    AppMingXiZuanShiDao appMingXiZuanShiDao;

    @Autowired
    AppMingxiFreetimeDao appMingxiFreetimeDao;

    @Autowired
    AppUserDressupDao appUserDressupDao;

    @Autowired
    AppSetupDao appSetupDao;

    @Autowired
    AppInvitationRecordDao appInvitationRecordDao;

    @Autowired
    AppOrderDao appOrderDao;

    @Autowired
    AppInvitationRecordService appInvitationRecordService;

    @Autowired
    AppSetupService appSetupService;

    @Autowired
    AppUserService appUserService;
    @Autowired
    RedisUtil redisUtil;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public List<AppPrivilege> guizuList(){
        return appPrivilegeDao.guizuList();
    }

    @Override
    public AppPrivilege get(Integer id){
        return appPrivilegeDao.get(id);
    }

    @Override
    public boolean isUpLevel(AppUser user) {
        if(user.getIsguizu() == 2) {
            //如果当前不是贵族
            AppPrivilege low = appPrivilegeDao.getLowOne();
            if(new BigDecimal(String.valueOf(user.getChongzhimoney())).compareTo(low.getUpCondition()) > 0) {
                //满足升第一级条件
                guizuKaitong(user, low);
            }
        } else if(user.getIsguizu() == 1) {
            AppPrivilege next = appPrivilegeDao.getNext(user.getNobleid());
            if(next != null && new BigDecimal(String.valueOf(user.getChongzhimoney())).compareTo(next.getUpCondition()) > 0) {
                //满足升下一级条件
                guizuKaitong(user, next);
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean guizuKaitong(AppUser user, AppPrivilege appPrivilege) {
        try {
            //变更用户贵族状态
            appUserDao.updateGuizu(user.getId(), appPrivilege.getId());
            String key = String.format(RedisKeys.USER, user.getId());
            redisUtil.del(key);
            //判断贵族是否赠送坐骑
            if (appPrivilege.getIszuoqi() == 1) {
                //赠送
                AppMounts mounts = appMountsDao.get(appPrivilege.getZuoqiid());
                if (!StringUtils.isEmpty(mounts)) {
                    AppUserDressup dressup = new AppUserDressup();
                    dressup.setState(2);
                    dressup.setMountsid(mounts.getId());
                    dressup.setBuyingtime(new Date());
                    dressup.setDay(mounts.getDay());
                    dressup.setType(1);
                    dressup.setOvertime(dateFormat.parse(getDay(mounts.getDay(), new Date())));
                    dressup.setUserid(user.getId());
                    dressup.setPhone(user.getLoginname());
                    dressup.setPic(user.getPic());
                    dressup.setGoodname(mounts.getName());
                    dressup.setGoodpic(mounts.getImgurl());
                    appUserDressupDao.save(dressup);
                }
            }
            //判断贵族是否赠送头饰
            if (appPrivilege.getIstoushi() == 1) {
                //赠送
                AppHeadwear headwear = appHeadwearDao.get(appPrivilege.getToushiid());
                if (!StringUtils.isEmpty(headwear)) {
                    AppUserDressup dressup = new AppUserDressup();
                    dressup.setState(2);
                    dressup.setMountsid(headwear.getId());
                    dressup.setBuyingtime(new Date());
                    dressup.setDay(headwear.getDay());
                    dressup.setType(2);
                    dressup.setOvertime(dateFormat.parse(getDay(headwear.getDay(), new Date())));
                    dressup.setUserid(user.getId());
                    dressup.setPhone(user.getLoginname());
                    dressup.setPic(user.getPic());
                    dressup.setGoodname(headwear.getName());
                    dressup.setGoodpic(headwear.getImgurl());
                    appUserDressupDao.save(dressup);
                }
            }
            //获取用户腾讯方最新的数据
            String re = TxIm.portraitGget(user.getTengxuncode());
            Integer headHalo = 0;
            Integer charmNum = 0;
            Integer status = 0;
            Integer isVip = 0;
            String headWear = "";
            if (!isNull(re)) {
                JSONObject jsonObject1 = JSON.parseObject(re);
                headHalo = jsonObject1.getInteger("headHalo");
                charmNum = jsonObject1.getInteger("charmNum");
                headWear = jsonObject1.getString("headWear");
                status = jsonObject1.getInteger("status");
                isVip = jsonObject1.getInteger("isVip");
            }
            //重新设置资料
            userSignVo vo1 = new userSignVo();
            vo1.setId(user.getId());
            vo1.setCharmNum(charmNum);
            vo1.setHeadWear(headWear);
            vo1.setHeadHalo(headHalo);
            vo1.setNobleid(appPrivilege.getId());
            vo1.setStatus(status);
            vo1.setIsVip(isVip);
            net.sf.json.JSONObject obj1 = net.sf.json.JSONObject.fromObject(vo1);
            UserShiZhi shiZhi = new UserShiZhi();
            shiZhi.setUserSign(obj1.toString());
            shiZhi.setTengxuncode(user.getTengxuncode() + "");
            TxIm.portraitSet(shiZhi);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }
}
